﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using System.Drawing;
using System.Security.Cryptography;
using System.Data.OleDb;
using System.Configuration;

namespace WeakEndForum
{
    public partial class Inscription : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void customValidSignupForm_ServerValidate(object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;
            string errorMessages = "";
            if (isStringValid(txtUsername.Text) && isStringValid(txtPassword.Text))
            {
                if (isEmailValid(txtEmail.Text))
                {
                    if (fuAvatar.PostedFile.ContentLength > 0)
                    {
                        if (fuAvatar.PostedFile.ContentType == "image/jpeg" || fuAvatar.PostedFile.ContentType == "image/jpg" || fuAvatar.PostedFile.ContentType == "image/png" || fuAvatar.PostedFile.ContentType == "image/gif")
                        {
                            Bitmap tempImg = new Bitmap(fuAvatar.PostedFile.InputStream);
                            if (tempImg.Height <= 180 && tempImg.Width <= 180)
                            {
                                args.IsValid = true;
                            }
                            else
                            {
                                errorMessages = ("L'image spécifiée est trop grande.");
                            }
                        }
                        else
                        {
                            errorMessages = ("Le fichier spécifié n'est pas une image.");
                        }
                    }
                    else
                    {
                        args.IsValid = true;
                    }
                }
                else
                {
                    errorMessages = ("L'adresse courriel est invalide.");
                }
            }
            else
            {
                errorMessages = ("Le nom d'utilisateur et le mot de passe doivent être spécifié.");
            }


            if (args.IsValid)
            {
                if (areInfosTaken() == false)
                {
                    RNGCryptoServiceProvider saleur = new RNGCryptoServiceProvider();
                    byte[] selCreated;
                    selCreated = new byte[24];
                    saleur.GetBytes(selCreated);

                    Rfc2898DeriveBytes hachoir = new Rfc2898DeriveBytes(txtPassword.Text, selCreated, 1500);
                    byte[] createdPass = hachoir.GetBytes(24);


                    OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
                    connection.Open();
                    if (fuAvatar.HasFile)
                    {
                        OleDbCommand addUser = new OleDbCommand("INSERT INTO Utilisateurs (Username,[Password],Image_Avatar,Sel,Email) VALUES (@username,@password,@image_avatar,@sel,@email)", connection);

                        addUser.Parameters.Add(new OleDbParameter("username", txtUsername.Text) { OleDbType = OleDbType.VarChar, Size = 255 });
                        addUser.Parameters.Add(new OleDbParameter("password", createdPass) { OleDbType = OleDbType.VarBinary, Size = 24 });
                        addUser.Parameters.Add(new OleDbParameter("image_avatar", (txtUsername.Text + fuAvatar.PostedFile.FileName)) { OleDbType = OleDbType.VarChar, Size = 255 });
                        addUser.Parameters.Add(new OleDbParameter("sel", selCreated) { OleDbType = OleDbType.VarBinary, Size = 24 });
                        addUser.Parameters.Add(new OleDbParameter("email", txtEmail.Text) { OleDbType = OleDbType.VarChar, Size = 255 });

                        addUser.Prepare();
                        addUser.ExecuteNonQuery();

                        fuAvatar.SaveAs(Server.MapPath(@"User_Data\images\" + txtUsername.Text + fuAvatar.PostedFile.FileName));

                    }
                    else
                    {
                        OleDbCommand addUserDefault = new OleDbCommand("INSERT INTO Utilisateurs (Username,[Password],Sel,Email) VALUES (@username,@password,@sel,@email)", connection);

                        addUserDefault.Parameters.Add(new OleDbParameter("username", txtUsername.Text) { OleDbType = OleDbType.VarChar, Size = 255 });
                        addUserDefault.Parameters.Add(new OleDbParameter("password", createdPass) { OleDbType = OleDbType.VarBinary, Size = 24 });
                        addUserDefault.Parameters.Add(new OleDbParameter("sel", selCreated) { OleDbType = OleDbType.VarBinary, Size = 24 });
                        addUserDefault.Parameters.Add(new OleDbParameter("email", txtEmail.Text) { OleDbType = OleDbType.VarChar, Size = 255 });

                        addUserDefault.Prepare();
                        addUserDefault.ExecuteNonQuery();
                    }
                    
                    Session["Username"] = txtUsername.Text;
                    OleDbCommand getImage = new OleDbCommand("SELECT Image_Avatar FROM Utilisateurs WHERE Username = @username", connection);
                    getImage.Parameters.Add(new OleDbParameter("username", txtUsername.Text) { OleDbType = OleDbType.VarChar, Size = 255 });
                    getImage.Prepare();
                    OleDbDataReader imageReader = getImage.ExecuteReader();
                    imageReader.Read();
                    Session["Image_Avatar"] = @"User_Data\images\" + (string)imageReader[0];
                    connection.Close();
                    Response.Redirect("~/Default.aspx");
                    
                }
                else
                {
                    lblErrors.Text = "Un usager existe déjà sous le même nom d'utilisateur ou l'adresse courriel spécifiés.";
                }
            }
            else
            {
                lblErrors.Text = errorMessages;
            }


        }

        private bool isStringValid(string _stringToValidate)
        {
            bool isValid = false;

            if (_stringToValidate.Trim() != "" && _stringToValidate != null)
            {
                isValid = true;
            }

            return isValid;
        }

        private bool isEmailValid(string _emailToValidate)
        {
            bool isValid = true;

            try
            {
                MailAddress email = new MailAddress(_emailToValidate);
                isValid = true;
            }
            catch
            {
                isValid = false;
            }
            return isValid;
        }

        private bool areInfosTaken()
        {
            bool isTaken = false;

            OleDbConnection connection = new OleDbConnection(ConfigurationManager.ConnectionStrings[Constantes.DB_NAME].ConnectionString);
            connection.Open();
            OleDbCommand verifyUser = new OleDbCommand("SELECT Username, Email FROM Utilisateurs WHERE Username = @username OR Email = @email", connection);

            verifyUser.Parameters.Add(new OleDbParameter("username", txtUsername.Text) { OleDbType = OleDbType.VarChar, Size = 255 });
            verifyUser.Parameters.Add(new OleDbParameter("email", txtEmail.Text) { OleDbType = OleDbType.VarChar, Size = 255 });

            verifyUser.Prepare();

            
            OleDbDataReader dataReader = verifyUser.ExecuteReader();

            if (dataReader.Read())
            {
                isTaken = true;
            }

            connection.Close();

            return isTaken;
        }
    }
}